package com.starnet.yarnmonitor.yarn.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.starnet.yarnmonitor.yarn.handler.ApiException;
import com.starnet.yarnmonitor.yarn.vo.param.PageParams;
import com.starnet.yarnmonitor.yarn.vo.result.PageVO;

import java.util.ArrayList;
import java.util.List;

public class PageUtils {
    /**
     * 将List转换成PageVo
     *
     * @param list 裁剪前的结果
     * @param cur  请求的第几页 从1开始
     * @param size 请求的当前页面尺寸
     */
    public static PageVO getPageVoFromList(List list, Integer cur, Integer size) {
        if (size != null && size <= 0) {
            throw new ApiException("页面大小非法");
        }
        PageVO pageVO = new PageVO();
        if (cur != null) {
            pageVO.setCur(cur);
        }
        if (size != null) {
            pageVO.setSize(size);
        }
        pageVO.setTotalRecords(list.size());
        //总页码
        int totalPages = (int) Math.ceil((double) list.size() / pageVO.getSize());
        pageVO.setTotalPages(totalPages);
        return pageVO;
    }

    public static List getPagedList(List list, Integer cur, Integer size) {
        if (cur == null) {
            cur = 1;
        }
        if (size == null) {
            size = 5;
        }
        List resList = new ArrayList();
        int start = (cur - 1) * size;
        if (start >= list.size()) {
            throw new ApiException("请求页面超出限制，该页面无内容");
        }
        for (int i = start, j = size; j > 0 && i < list.size(); i++, j--) {
            resList.add(list.get(i));
        }
        return resList;

    }

    public static <T> IPage<T> getIPage(Integer cur, Integer size, Class<T> tClass) {
        cur = cur == null ? PageParams.page : cur;
        size = size == null ? PageParams.pageSize : size;
        IPage<T> iPage = new Page<>();
        iPage.setCurrent(cur);
        iPage.setSize(size);
        return iPage;
    }

    public static PageVO getPageVOFromIPage(IPage page){
        PageVO pageVO = new PageVO();
        pageVO.setCur(page.getCurrent());
        //当前页面尺寸
        pageVO.setSize(page.getSize());
        //总记录数
        pageVO.setTotalRecords(page.getTotal());
        //算出总页面
        pageVO.setTotalPages((long) Math.ceil((double) page.getTotal()/(double) page.getSize()));
        return pageVO;
    }
}
